package com.bwie.service.impl;

import cn.hutool.core.util.EscapeUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.TbOrderDetailMapper;
import com.bwie.mapper.TbOrderRecordMapper;
import com.bwie.mapper.TbProdInfoMapper;
import com.bwie.poi.ExcelUtil;
import com.bwie.poi.StringUtils;
import com.bwie.pojo.TbOrder;
import com.bwie.pojo.TbOrderDetail;
import com.bwie.pojo.TbOrderRecord;
import com.bwie.pojo.TbProdInfo;
import com.bwie.service.TbOrderService;
import com.bwie.mapper.TbOrderMapper;
import com.bwie.utils.R;
import com.bwie.vo.PageInfoVo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
* @author 31439
* @description 针对表【tb_order(订单表)】的数据库操作Service实现
* @createDate 2025-07-23 14:09:22
*/
@Service
public class TbOrderServiceImpl extends ServiceImpl<TbOrderMapper, TbOrder>
    implements TbOrderService{

    @Autowired
    TbOrderMapper tbOrderMapper;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    RedissonClient redissonClient;

    @Autowired
    TbProdInfoMapper tbProdInfoMapper;

    @Autowired
    TbOrderRecordMapper tbOrderRecordMapper;

    @Autowired
    TbOrderDetailMapper tbOrderDetailMapper;

    @Autowired
    HttpServletResponse response;
    @Override
    public R getOrderList(PageInfoVo pageInfoVo) {
        Page<TbOrder> page = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());
        QueryWrapper<TbOrder> wrapper = new QueryWrapper<>();
        //关键字
        if(StringUtils.isNotEmpty(pageInfoVo.getKeyWord())){
            wrapper.lambda().like(TbOrder::getProdInfo,pageInfoVo.getKeyWord())
                    .or()
                    .eq(TbOrder::getOrderId,pageInfoVo.getKeyWord());
        }

        //状态
        if(pageInfoVo.getStatus() != null){
            wrapper.lambda().eq(TbOrder::getOrderStatus,pageInfoVo.getStatus());
        }

        //类型
        if(pageInfoVo.getOrderType() != null){
            wrapper.lambda().eq(TbOrder::getOrderType,pageInfoVo.getOrderType());
        }
        wrapper.lambda().orderByAsc(TbOrder::getOrderId);

        Page<TbOrder> tbOrderPage = tbOrderMapper.selectPage(page, wrapper);

        for (TbOrder record : tbOrderPage.getRecords()) {
            List<String> imagesList = tbOrderMapper.getOrderImageList(record.getOrderId());
            ArrayList<String> imageList = new ArrayList<>();
            if(imagesList != null && imagesList.size() > 0){
                for (String s : imagesList) {
                    if(s != null){
                        List<String> list = JSON.parseArray(s, String.class);
                        imageList.addAll(list);
                    }
                }
            }
            record.setImageList(imageList);
        }

        return R.OK(tbOrderPage);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R addOrder(List<TbProdInfo> infoList) {

        //检查库存，并扣减库存
        BigDecimal totalAmount = new BigDecimal("0");
        StringBuilder prodNames = new StringBuilder();
        //获取分布式值
        RLock lock = redissonClient.getLock("order-lock");
        try {
            //加锁
            lock.lock();
            for (TbProdInfo tbProdInfo : infoList) {
                TbProdInfo prodInfo = tbProdInfoMapper.selectById(tbProdInfo.getInfoId());
                if(tbProdInfo.getBuyNum() > prodInfo.getProdStock()){
                    throw new RuntimeException("库存不足");
                }
                //扣减库存
                prodInfo.setProdStock(prodInfo.getProdStock()-tbProdInfo.getBuyNum());
                tbProdInfoMapper.updateById(prodInfo);

                //计算订单金额
                totalAmount = totalAmount.add(tbProdInfo.getCostPrice().multiply(new BigDecimal(tbProdInfo.getBuyNum())));
                //拼接商品名称
                if(prodNames.length() > 0){
                    prodNames.append(",");
                    prodNames.append(tbProdInfo.getProdName());
                }else{
                    prodNames.append(tbProdInfo.getProdName());
                }
            }
        }finally {
            //解锁
            lock.unlock();
        }


        //创建订单
        TbOrder tbOrder = new TbOrder();
        //雪花算法生成订单号
        long id = IdUtil.getSnowflake(1, 1).nextId();
        tbOrder.setOrderNo(""+id);

        tbOrder.setOrderType(1);
        tbOrder.setOrderStatus(0);
        tbOrder.setCreateTime(new Date());
        tbOrder.setCreateBy("张三");
        tbOrder.setOrderAmount(totalAmount);
        tbOrder.setProdInfo(prodNames.toString());
        tbOrder.setUserId(1);

        tbOrderMapper.insert(tbOrder);

        //创建订单明细
        for (TbProdInfo tbProdInfo : infoList) {
            TbOrderDetail tbOrderDetail = new TbOrderDetail();
            //关联订单
            tbOrderDetail.setOrderId(tbOrder.getOrderId());
            tbOrderDetail.setBuyNum(tbProdInfo.getBuyNum());
            tbOrderDetail.setProdPrice(tbProdInfo.getProdPrice());
            tbOrderDetail.setInfoId(tbProdInfo.getInfoId());

            tbOrderDetailMapper.insert(tbOrderDetail);
        }

        //新增订单记录
        TbOrderRecord tbOrderRecord = new TbOrderRecord();
        tbOrderRecord.setOrderId(tbOrder.getOrderId());
        tbOrderRecord.setOptRecord("用户创建订单");
        tbOrderRecord.setCreateTime(new Date());

        tbOrderRecordMapper.insert(tbOrderRecord);

        return R.OK();
    }

    @Override
    public R exportOrderList(Integer userId) {

        List<TbOrder> tbOrderList = tbOrderMapper.selectList(
                new QueryWrapper<TbOrder>().lambda().eq(TbOrder::getUserId, userId)
        );
        //创建导出工具
        ExcelUtil<TbOrder> excelUtil = new ExcelUtil<>(TbOrder.class);
        excelUtil.exportExcel(response,tbOrderList,"订单列表");
        return R.OK(excelUtil);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R deleteOrder(List<Integer> ids) {
        //批量删除订单
        tbOrderMapper.deleteBatchIds(ids);

        //批量删除订单信息表
        tbOrderDetailMapper.delete(
                new QueryWrapper<TbOrderDetail>().lambda().in(TbOrderDetail::getOrderId,ids)
        );

        return R.OK();
    }


}




